//
//  LZCartPayViewController.m
//  com.modada.new
//
//  Created by ferver7 on 2019/5/19.
//  Copyright © 2019 ferver7. All rights reserved.
//

#import "LZCartPayViewController.h"
#import "SelAddressCell.h"
#import "SelAddressCell.h"
#import "OrderStoreInfoCell.h"
#import "OrderFirstKindCell.h"
#import "OrderTwoKindCell.h"
#import "LZPayGoodsCell.h"
#import "OrderConfigCell.h"
#import "LZPaySelCounView.h"
#import "MDDOrderDetailViewController.h"
#import "MDDAddressViewController.h"
#import "OrderPayMoneyCell.h"


@interface LZCartPayViewController ()<OrderConfigCellDelegate>

@property (weak, nonatomic) IBOutlet UIButton *sureSumitAction;
@property (weak, nonatomic) IBOutlet UITableView *selfTableView;
@property (nonatomic,strong) NSString *addressId;
@property (nonatomic,strong) NSArray *cardList;
@property (nonatomic,strong) NSIndexPath *remarkPath;

@property (nonatomic,copy) NSString *cardId;
@property (nonatomic,copy) NSString *paymentMethod;//运送方式
@property (nonatomic,assign) float yunfeiM;//实际运费
@property (nonatomic,assign) float yunfeiMMMM;//如果选择送货上门，应付运费

@property (nonatomic,assign) float totlePrice;//商品总价格
@property (nonatomic,assign) float youhuiMoney;//优惠价格
@property (nonatomic,assign) BOOL nopeYouhui;//不使用优惠券

@property (nonatomic,strong) AddressListModel *selModel;

@end

@implementation LZCartPayViewController
- (IBAction)sureAciton:(id)sender {
    NSMutableDictionary * requestDic = [[NSMutableDictionary alloc]init];
    NSMutableArray * listArr = [[NSMutableArray alloc]init];
    for (int i = 0; i<[self.payInfo[@"storeVOS"] count]; i++) {
        NSMutableDictionary * parameters = [[NSMutableDictionary alloc]init];
        NSDictionary * storeInfo = self.payInfo[@"storeVOS"][i];
        NSMutableArray * shopGoodId = [[NSMutableArray alloc]init];
        for (NSDictionary * goodInfo in storeInfo[@"goods"]) {
            for (NSDictionary * detailInfo in goodInfo[@"attList"]) {
                [shopGoodId addObject:detailInfo[@"shoppingCartId"]];
            }
        }
        OrderConfigCell * itemCell = [self.selfTableView  cellForRowAtIndexPath:[NSIndexPath indexPathForRow:self.remarkPath.row inSection:self.remarkPath.section]];
        NSString *remark =@"" ;
        remark =  itemCell ?  itemCell.beiZhu.text:@"" ;
    
        setDickeyobj(parameters, shopGoodId, @"shoppingCartId");
        setDickeyobj(parameters, self.cardId, @"cardId");//优惠券id
        setDickeyobj(parameters, storeInfo[@"storeId"], @"storeid");
        if (self.selModel) {
            setDickeyobj(parameters, self.selModel.aid, @"aid");
        }
        
//        deliveryMethod (integer, optional): 配送方式 0 送货上门 1 自提 ,
//        paymentMethod (integer, optional): 付款方式： 0 货到付款 ,
        
        setDickeyobj(parameters, self.paymentMethod , @"deliveryMethod");//配送方式 默认是送货上门 0。 自提是1
        setDickeyobj(parameters, remark, @"remark");//留言
        setDickeyobj(parameters, @"0", @"paymentMethod");//付款方式  现在只有 货到付款
        [listArr addObject:parameters];
    }
    setDickeyobj(requestDic, listArr, @"list");
    [PPNetworkHelper POST:app_order_submit parameters:requestDic success:^(id responseObject) {
        if (YJPPSUCCESS(responseObject)) {
            MDDOrderDetailViewController * odvc =mGetStoryboardViewController(@"Main", @"mDDOrderDetailViewController");
            odvc.orderNo = [responseObject[@"data"] firstObject];
            odvc.isCart = YES;
            NavigationController_pushVC(odvc);
        }else{
            [AxcUI_Toast AxcUI_showCenterWithText:responseObject[@"msg"]];
        }
    } failure:^(NSError *error) {
        
    } showLoading:nil];
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.cardId = @"";
    _youhuiMoney= 0;
    _totlePrice = 0;
    self.nopeYouhui= 0;
    self.paymentMethod = @"0"; //  配送方式 0 送货上门 1 自提 ,
    [self customNavigationItems];
    self.view.backgroundColor = [UIColor AxcUI_colorWithHexCode:@"#ebebeb"];
    mNavitationTitle(@"确认订单");
    self.cardList = self.payInfo[@"cardList"];
}
#pragma mark -
#pragma mark - **************** tableViewDelegate
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1+[self.payInfo[@"storeVOS"] count] +1; //最后这个加1是订单总和部分的cell;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return 2;
    }else if (section >= 1 && section <= [self.payInfo[@"storeVOS"] count]){
        NSDictionary *storeInfo = self.payInfo[@"storeVOS"][section-1];
        NSArray * goods = storeInfo[@"goods"];
        return 2+goods.count;
    }
    return 1;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        if (indexPath.row == 0 ) {
            UITableViewCell * baseCell = mGetTableViewCell(@"firstLine");
            UIImageView * logo = mViewByTag(baseCell.contentView, 100, UIImageView);
            logo.image = mImageByName(@"收货信息变更");
            
            UILabel * title = mViewByTag(baseCell.contentView, 101, UILabel);
            title.text = @"收货信息";
            return baseCell;
        }else{
            SelAddressCell * sac = mGetTableViewCell(@"selAddressCell");
            NSDictionary *addressInfo = self.payInfo[@"addressVO"];
            if (addressInfo) {
                self.selModel = [[AddressListModel alloc]init];
                [self.selModel setValuesForKeysWithDictionary:addressInfo];
            }
            if (self.selModel) {
                sac.bgLabel.hidden = YES;
                [sac reloadViewForModel:self.selModel];
            }else{
                sac.bgLabel.hidden = NO;
            }
            return sac;
        }
    }else if (indexPath.section <=[self.payInfo[@"storeVOS"] count]){
        NSDictionary *storeInfo = self.payInfo[@"storeVOS"][indexPath.section-1];
        NSArray * goods = storeInfo[@"goods"];
        if (indexPath.row == 0) {
            OrderStoreInfoCell * itemCell = mGetTableViewCell(@"orderStoreInfoCell");
            NSDictionary *storeInfo = self.payInfo[@"storeVOS"][indexPath.section -1];
//            orderType 订单类型or店铺类型：1商家，2专营 ,
            if ([storeInfo[@"storeType"] isEqualToString:@"1"]) {
                itemCell.stateLabel.text = @"商家";
            }else{
                itemCell.stateLabel.text = @"专营";
            }
            if ([storeInfo[@"freescope"] integerValue] == -1) {
                itemCell.mianFeiLabel.text = @"免费配送";
            }else{
                itemCell.mianFeiLabel.text = [NSString stringWithFormat:@"(%@公里内免费配送)",storeInfo[@"freescope"]];
            }
            itemCell.storeNameLabel.text = storeInfo[@"storeName"];
            return itemCell;
        }else if (indexPath.row <=goods.count){
            LZPayGoodsCell * itemCell = mGetTableViewCell(@"lZPayGoodsCell");
            NSDictionary *storeInfo = self.payInfo[@"storeVOS"][indexPath.section -1];
            NSDictionary * goods = storeInfo[@"goods"][indexPath.row-1];
           
            [itemCell.iconImage sd_setImageWithURL:[NSURL URLWithString:goods[@"thumbnail"]] placeholderImage:mImageByName(@"")];
            itemCell.kindName.text = goods[@"typeName"];
            itemCell.goodArr = goods[@"attList"];
            
            return itemCell;
        }else{
            OrderConfigCell * itemCell = mGetTableViewCell(@"orderConfigCell");
            itemCell.delegate = self;
            itemCell.path = indexPath;
            self.remarkPath= indexPath;
            NSDictionary *storeInfo = self.payInfo[@"storeVOS"][indexPath.section-1];
            NSArray * goods = storeInfo[@"goods"];
            int countGoods = 0;
            double totlePrice = 0.0;
            for (NSDictionary * infoDic in goods) {
                for (NSDictionary * objInfo in infoDic[@"attList"]) {
                    countGoods += 1;
                    totlePrice += [objInfo[@"quantity"] intValue] *[objInfo[@"price"] floatValue];
                }
            }
            self.totlePrice = totlePrice;
//            NSString *string = [NSString stringWithFormat:@"￥%.2f",totlePrice];
            CGFloat yunFei = ([storeInfo[@"distance"] integerValue]-[storeInfo[@"freescope"] integerValue])*[storeInfo[@"fee"] floatValue];
            if (yunFei<=0) {
                self.yunfeiMMMM = 0;
            }else{
                self.yunfeiMMMM = yunFei;
            }
            if ([self.paymentMethod isEqualToString:@"1"]) {//自提 运费0
                yunFei=0;
            }else{//非自提 运费要算
                if (yunFei<=0) {
                    yunFei=0;
                }
            }
            self.yunfeiM =yunFei;
            itemCell.yuFeiLabel.text = [NSString stringWithFormat:@"送货上门: %.2lf",yunFei];
            if (self.youhuiMoney) {
                itemCell.youHuiLabel.text = [NSString stringWithFormat:@"%.2f",self.youhuiMoney];
            }else if (self.nopeYouhui) {
                itemCell.youHuiLabel.text = @"不使用优惠券";
            }else if (self.cardList.count == 0) {
                itemCell.youHuiLabel.text = @"暂无优惠券";
            }else if(self.cardList.count > 0 ){
                itemCell.youHuiLabel.text = @"请选择优惠券";
            }
            WS(weakSelf);
            itemCell.selYouHuiBlock = ^{//选择优惠券
                CGFloat yunFei = ([storeInfo[@"distance"] integerValue]-[storeInfo[@"freescope"] integerValue])*[storeInfo[@"fee"] floatValue];
                if ([self.paymentMethod isEqualToString:@"1"]) {//自提 运费0
                    yunFei=0;
                }else{//非自提 运费要算
                    if (yunFei<=0) {
                        yunFei=0;
                    }
                }
                self.yunfeiM =yunFei;
                
                LZPaySelCounView * selfCounView = [[NSBundle mainBundle]loadNibNamed:@"LZPaySelCounView" owner:nil options:nil].firstObject;
                selfCounView.cardList = weakSelf.cardList;
                selfCounView.axcUI_Size = CGSizeMake(mScreenWidth, 400);
                selfCounView.axcUI_rectCorner = UIRectCornerTopLeft | UIRectCornerTopRight;
                selfCounView.axcUI_rectCornerRadii = 6;
                selfCounView.returnSelResule = ^(id  _Nonnull cardInfo) {
                    CGFloat youhuiMoney;
                    if ([cardInfo isKindOfClass:[NSDictionary class]]) {
                        youhuiMoney = [cardInfo[@"money"] floatValue];
                        itemCell.youHuiLabel.text = [NSString stringWithFormat:@"-¥%@",cardInfo[@"money"]];
                        weakSelf.cardId =cardInfo[@"cardId"];
                    }else{
                        itemCell.youHuiLabel.text = @"不使用优惠券";
                        self.nopeYouhui = 1;
                        youhuiMoney = 0;
                        weakSelf.cardId = @"";
                    }
                    _youhuiMoney = youhuiMoney;
                    itemCell.totalMoneyLabel.text = [NSString stringWithFormat:@"¥%.2lf",totlePrice+yunFei-youhuiMoney];
                    itemCell.yuFeiLabel.text = [NSString stringWithFormat:@"%@ ¥%.2lf",[weakSelf.paymentMethod isEqualToString:@"1"] ? @"上门自提":@"送货上门",yunFei];
                    
                    NSIndexSet *indexSet=[[NSIndexSet alloc]initWithIndex:1+[self.payInfo[@"storeVOS"] count]];
                    [tableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationFade];
                    [GKCover hide];
                };
                [GKCover translucentCoverFrom:mKeyWindow content:selfCounView animated:YES showBlock:^{
                    
                } hideBlock:^{
                    
                }];
            };
            itemCell.totalLabel.text = [NSString stringWithFormat:@"共 %d 种商品",countGoods];
            itemCell.totalMoneyLabel.text = [NSString stringWithFormat:@"¥%.2lf",totlePrice+yunFei-self.youhuiMoney];
            return itemCell;
        }
    }else if(1+[self.payInfo[@"storeVOS"] count]){
        
        OrderPayMoneyCell * itemCell = mGetTableViewCell(@"orderPayMoneyCell");
        
        
        itemCell.youHui.text = [NSString stringWithFormat:@"%.2f",self.youhuiMoney];
        itemCell.yunFei.text = [NSString stringWithFormat:@"运费总计:%.2f",self.yunfeiM];
        itemCell.totalPrice.text = [NSString stringWithFormat:@"合计(含运费):%.2f",self.totlePrice+self.yunfeiM-self.youhuiMoney];
        itemCell.allLab.text = [NSString stringWithFormat:@"订单总额(含运费):%.2f",self.totlePrice+self.yunfeiM-self.youhuiMoney];

        return itemCell;
    }
    
    return nil;
}
-(CGFloat )tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (indexPath.section == 0) {
        if (indexPath.row == 0 ) {
            return 44;
        }
        return 80;
    }else if (indexPath.section <=[self.payInfo[@"storeVOS"] count]){
        NSDictionary *storeInfo = self.payInfo[@"storeVOS"][indexPath.section-1];
        NSArray * goods = storeInfo[@"goods"];
        if (indexPath.row == 0) {
            return 40;
        }else if (indexPath.row <=goods.count){
            NSDictionary *storeInfo = self.payInfo[@"storeVOS"][indexPath.section -1];
            NSDictionary * goods = storeInfo[@"goods"][indexPath.row-1];
            return [goods[@"attList"] count]*80+50;
        }
    }else if(1+[self.payInfo[@"storeVOS"] count]){//OrderPayMoneyCell的高度
        return 140;
    }
    return 200;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 10;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0.01;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0 && indexPath.row == 1) {
        MDDAddressViewController * malvc = mGetStoryboardViewController(@"Main", @"mDDAddressViewController");
        WS(weakSelf);
        malvc.returnAddressBlock = ^(AddressListModel *addressModel) {
            weakSelf.selModel = addressModel;
            SelAddressCell * selcell = [tableView cellForRowAtIndexPath:indexPath];
            [selcell reloadViewForModel:addressModel];
            [weakSelf.navigationController  popViewControllerAnimated:YES];
        };
        [self.navigationController pushViewController:malvc animated:YES];
    }
}
#pragma mark ---- cell的代理方法
-(void)yunfeiAction:(NSIndexPath *)path{
    
    
    LZPaySelCounView * selfCounView = [[NSBundle mainBundle]loadNibNamed:@"LZPaySelCounView" owner:nil options:nil].firstObject;
    
    
    selfCounView.yunfeiArr = @[@"上门自提 0元",[NSString stringWithFormat:@"送货上门 ¥%.2f",self.yunfeiMMMM]];
    selfCounView.axcUI_Size = CGSizeMake(mScreenWidth, 400);
    selfCounView.axcUI_rectCorner = UIRectCornerTopLeft | UIRectCornerTopRight;
    selfCounView.axcUI_rectCornerRadii = 6;
    selfCounView.returnSelResule = ^(id  _Nonnull cardInfo) {

        OrderConfigCell * itemCell = [self.selfTableView  cellForRowAtIndexPath:[NSIndexPath indexPathForRow:path.row inSection:1]];
        itemCell.yuFeiLabel.text = (NSString *)cardInfo;
        if ([itemCell.yuFeiLabel.text isEqualToString:@"上门自提 0元"]) {  // 配送方式 0 送货上门 1 自提 ,
            self.paymentMethod= @"1";
            itemCell.yuFeiLabel.text = @"上门自提 0元";
            self.yunfeiM = 0;
            itemCell.totalMoneyLabel.text = [NSString stringWithFormat:@"¥%.2lf",self.totlePrice-self.youhuiMoney];

        }else{
            self.paymentMethod= @"0";
            itemCell.totalMoneyLabel.text = [NSString stringWithFormat:@"¥%.2lf",self.totlePrice-self.youhuiMoney+self.yunfeiMMMM];

        }
        
        NSIndexSet *indexSet=[[NSIndexSet alloc]initWithIndex:1+[self.payInfo[@"storeVOS"] count]];
        [self.selfTableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationFade];
        [GKCover hide];
    };
    
    [GKCover translucentCoverFrom:mKeyWindow content:selfCounView animated:YES showBlock:^{
        
    } hideBlock:^{
        
    }];

}

@end
